package com.service.user.impl;

import com.dao.OthersDao;
import com.entity.Notice;
import com.service.user.NoticeService;
import com.service.user.OtherService;
import com.utils.FileUploadUtil;
import com.utils.SqlSessionGetter;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/** 提供系统相对比较简单独立的一些功能实现，如获取类别、标签、系统使用反馈等等 */
@Service
public class OtherServiceImpl implements OtherService {

  private static List<Map<String, Object>> types = null;
  @Autowired NoticeService noticeService;

  /**
   * 获取所有类别
   *
   * @return 类别列表，每个类别表示为{id: ,name: , subList: }
   */
  @Override
  public List<Map<String, Object>> getAllTypes() {
    if (types != null) {
      return types;
    }
    SqlSession session = SqlSessionGetter.getSqlSession();
    OthersDao dao = session.getMapper(OthersDao.class);
    types = dao.selectCategories();
    session.close();
    return types;
  }

  /**
   * 获取所有标签
   *
   * @return 标签列表
   */
  @Override
  public List<Map<String, String>> getAllLabels() {
    SqlSession session = SqlSessionGetter.getSqlSession();
    OthersDao dao = session.getMapper(OthersDao.class);
    List<Map<String, String>> allLabels = dao.getAllLabels();
    session.close();
    return allLabels;
  }

  @Override
  public int feedback(
      String userId,
      String title,
      String content,
      MultipartFile pic1,
      MultipartFile pic2,
      MultipartFile pic3) {
    String fbId = UUID.randomUUID().toString().replace("-", "");
    String pic1URL = null;
    if (pic1 != null){
      pic1URL =  FileUploadUtil.uploadFile(
              pic1, fbId + "1", FileUploadUtil.FEEDBACK_SUBDIR, FileUploadUtil.IMAGE_SUFFIX);
    }

    String pic2URL = null;
    if (pic2 != null)
      pic2URL =  FileUploadUtil.uploadFile(
            pic2, fbId + "2", FileUploadUtil.FEEDBACK_SUBDIR, FileUploadUtil.IMAGE_SUFFIX);
    String pic3URL = null;
    if (pic3 != null)
      pic3URL = FileUploadUtil.uploadFile(
            pic3, fbId + "3", FileUploadUtil.FEEDBACK_SUBDIR, FileUploadUtil.IMAGE_SUFFIX);

    SqlSession session = SqlSessionGetter.getSqlSession();
    OthersDao dao = session.getMapper(OthersDao.class);
    int row = dao.insertFeedback(userId, title, content, pic1URL, pic2URL, pic3URL);
    session.commit();
    session.close();
    noticeService.addNotice(
        userId, Notice.FEEDBACK, null, 1, title, content, pic1URL, pic2URL, pic3URL);
    return row;
  }
}
